package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.Redisson;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RSemaphore;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    Redisson redisson;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    CategoryService categoryService;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
        //TODO 1、查出所有的1级分类
        List<CategoryEntity> categoryEntities = categoryService.getLevel1Category();
        //视图解析器进行拼串
        //classpath:/templates/+ 返回值 + .html
        model.addAttribute("categorys",categoryEntities);
        return "index";
    }

    //index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String,List<Catelog2Vo>> getCatalogJson(){  //返回的map就是一个json对象
        Map<String,List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }


    @ResponseBody
    @GetMapping("/hello")
    public String hello()  {
        //1、获取一把锁,只要锁的名字一样,就是同一把锁
        RLock rLock= redisson.getLock("my-lock");
        //2、加锁
        rLock.lock(); //阻塞式等待,默认加的锁都是30s时间
        //1）、锁的自动续期,如果业务超长,运行期间自动给锁续上30s的时间,不会担心业务时间长,锁自动过期被删除掉
        //2）、加锁的业务只要运行完成,就不会给当前锁续期,即使不手动解锁,锁默认会在30s以后自动删除
//        rLock.lock(10, TimeUnit.SECONDS); // 10秒后自动解锁,自动解锁时间一定要大于业务的执行的时间
        //问题: lock(10, TimeUnit.SECONDS); 在锁时间到了以后,不会自动续期
        //1、如果我们传递了锁的时间,就发送给redis执行脚本,进行占锁,默认超时就是我们指定的时间
        //2、如果我们未指定超时时间,就会使用30*1000 【LockWatchdogTimeOut看门狗的默认时间】
        //  只要占锁成功,就会启动一个定时任务【重新给锁设置过期时间,新的过期时间就是看门狗默认的时间】
        // internalLockLeaseTime【看门狗时间】 /3  ,10s

        //最佳实战
        //1)、 lock.lock(30,TimeUtils.SECONDS); 省掉了整个续期操作,手动解锁
        try{
            System.out.println("加锁成功.执行业务代码"+Thread.currentThread().getId());
            Thread.sleep(30000);
        }catch(Exception e){

        } finally {
            //3、解锁
            System.out.println("释放锁...."+Thread.currentThread().getId());
            rLock.unlock();
        }
        return "hello";
    }
    // 保证一定能读到最新的数据,修改期间,写锁是一个排他锁,读锁是一个共享锁
    //写锁没释放就必须等待
    @GetMapping("/write")
    @ResponseBody
    public String writeValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = lock.writeLock();
        try{
            //1、该数据加写锁,读数据加读锁
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeValue",s);
        }catch( Exception e){
            e.printStackTrace();
        }finally{
            rLock.unlock();
        }
        return s ;
    }


    @GetMapping("/read")
    @ResponseBody
    public String readValue(){
        RReadWriteLock lock = redisson.getReadWriteLock("rw-lock");
        String s = "";
        //加读锁
        RLock rlock = lock.readLock();
        rlock.lock();
        try{

          s = String.valueOf(redisTemplate.opsForValue().get("writeValue"));
        }catch( Exception e){
            e.printStackTrace();
        }finally{
            rlock.unlock();
        }
        return s ;
    }
    /**
     * 放假,锁门
     * 1班没人了,2
     * 5个班全部走完,可以锁大门
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException{
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.trySetCount(5);
        door.await();//等待闭锁完成
        return "放假了";
    }

    @GetMapping("/gogogo/{id}")
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redisson.getCountDownLatch("door");
        door.countDown();//计数减一
        return id+"班的人都走了...";
//        Semaphore semaphore = new Semaphore(5);
//        semaphore.release();
//        semaphore.acquire();
    }
    /**
     * 车库停车
     * 3车位
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park  = redisson.getSemaphore("park");
        park.acquire(); //获取一个信号,占一个车位
        park.tryAcquire(); //获取一个信号值为true和false
        return "ok";
    }
    @GetMapping("/go")
    @ResponseBody
    public String go(){
        RSemaphore park = redisson.getSemaphore("park");
        park.release();// 释放一个车位
        return "ok";
    }
}
